package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NewsDao;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.service.INewsService;
import com.cn.wanxi.service.NewsService;
import com.cn.wanxi.util.IOTool;
import com.cn.wanxi.util.Path;
import com.cn.wanxi.util.Tool;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NewsServiceImpl implements INewsService {


    @Override
    public NewsModel[] getNewsModelForHomePage() {
//        1.创建文件
        File file = IOTool.createFile(Path.PATH, Path.DIRECTORY, Path.NEWS_FOR_HOME_PAGE);
//        2.封装dao层数据
        List<String> list = setDaoData();
//        3.写入文件数据
        IOTool.writeData(file, list);
//        4.读取数据
        String string = IOTool.readData(file);
//        5.封装前端需要的数据
        NewsModel[] newsModels = setData(string);
        return newsModels;
    }

    public static void main(String[] args) {
        new NewsServiceImpl().getNewsModelForHomePage();
    }

    private NewsModel[] setData(String string) {
//        NewsDao newsDao = new NewsDao();
        System.out.println(string);
        String[] results = string.split(Path.SPILT);
        int length = 3;
        NewsModel[] newsModels = new NewsModel[length];
        String idString = results[2];
        String title = results[1];
        String content = results[0];
//        将所有id的字符串转换数组，因为转换后全是字符串，所以需要将其转换为整型
        String[] idss = Tool.replace(idString).split(", ");
//       非数字 字符串不能转换为整型
        Integer[] ids = new Integer[3];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = Integer.parseInt(idss[i]);//将字符串转换为整型并复制给ids；
        }
//        Integer[] ids = Tool.replace(idString).split(", ");
        String[] contents = Tool.replace(content).split(", ");
        title = Tool.replace(title);//调用工具类里面的替换方法将[]去掉
        String[] titles = title.split(", ");//通过, 将字符串进行分组
        for (int i = 0; i < length; i++) {
            NewsModel model = new NewsModel();
            model.setId(ids[i]);
            model.setContent(contents[i]);
            model.setTitle(titles[i]);
            newsModels[i] = model;
        }
        return newsModels;
    }

    private List<String> setDaoData() {
        List<String> list = new ArrayList<>();
        NewsDao newsDao = new NewsDao();
        list.add(Arrays.toString(newsDao.titles));
        list.add(Arrays.toString(newsDao.contents));
        list.add(Arrays.toString(newsDao.ids));
        return list;
    }
}
